<template>
  <view class="scan">
    <view class="pt-4">请将二维码置于中央</view>
    <view class="video-container">
      <Video class="video" id="video-1" ref="video" autoplay />
    </view>
  </view>
</template>

<script>
import { BrowserMultiFormatReader, ChecksumException, FormatException } from '@zxing/library'
import { getOrderList, putOrderAbstract } from '@/services/apis/order'
import Taro from '@tarojs/taro'
import { useStore } from '@/stores'
import dayjs from 'dayjs'

const auth = useStore('auth')

export default {
  name: 'Scan',
  data() {
    return {
      codeReader: new BrowserMultiFormatReader(),
      videoInputDevices: [],
      currentVideoInputDevice: {},
      decodeResult: undefined,
      shopList: [],
      //节流
      lastTime: new Date()
    }
  },
  methods: {
    // 节流函数
    throttle(fun) {
      //函数执行时的时间
      let now = new Date()
      console.log('now', now)
      console.log('lastTime', this.lastTime)
      //两次调用的时间差
      if (now - this.lastTime > 2000) {
        fun()
        //调用成功，上一次调用时间值修改
        this.lastTime = now
      }
    },
    async openScan() {
      const _this = this
      _this.codeReader
        .getVideoInputDevices() // 老版本listVideoInputDevices()
        .then(videoInputDevices => {
          if (videoInputDevices && videoInputDevices.length) {
            if (videoInputDevices.length > 1) {
              videoInputDevices.reverse()
            } // 防止先唤出前摄像头
            _this.videoInputDevices = videoInputDevices
            _this.currentVideoInputDevice = videoInputDevices[0]
          }
        })
        .catch(() => {})
    },

    decodeFromInputVideo() {
      const _this = this
      _this.codeReader.reset()
      // 多次
      _this.codeReader.decodeFromVideoDevice(
        _this.currentVideoInputDevice.deviceId,
        'video-1',
        (result, err) => {
          if (result) {
            _this.decodeResult = result
          }
          if (err) {
            if (err instanceof ChecksumException) {
              console.log("A code was found, but it's read value was not valid.")
            }
            if (err instanceof FormatException) {
              console.log('A code was found, but it was in a invalid format.')
            }
          }
        }
      )
    },

    successDecode() {
      const _this = this
      console.log(_this.decodeResult.text, '_this.decodeResult.text')
      if (_this.decodeResult.text) {
        _this.throttle(function() {
          //1000ms内无论点击多少下，只会调用一次
          _this.getOrderList(_this.decodeResult.text)
        })
      }
    },

    getOrderList(context) {
      const data = {
        storeID: Taro.getStorageSync('storeID'),
        beginDate: 1000000000,
        endDate: dayjs(new Date()).unix(),
        dateOptions: 2,
        sortOptions: 1,
        searchField: 5,
        searchContent: context
      }
      console.log(data, 'data')
      getOrderList(data).then(res => {
        this.shopList = res.data.list
        if (this.shopList.length > 0) {
          if (this.shopList[0].orderStatus === 2) {
            this.putOrderAbstract(this.shopList[0].orderNo)
          } else {
            Taro.showToast({
              title: '订单已核销，可以进入订单',
              icon: 'none',
              duration: 1000
            })
          }
        } else {
          Taro.showToast({
            title: '未查到该订单',
            icon: 'none',
            duration: 1000
          })
        }
      })
    },
    putOrderAbstract(orderNo) {
      putOrderAbstract({ orderNo: orderNo, status: 3 }).then(res => {
        if (this.shopList.length > 0) {
          Taro.showToast({
            title: '核销成功',
            icon: 'none',
            duration: 1000
          })
          // this.$message.sucess('核销成功');
        }
      })
      this.shopList = []
    }
  },
  watch: {
    currentVideoInputDevice: function() {
      this.decodeFromInputVideo()
    },
    decodeResult: function() {
      this.successDecode()
    }
  },
  mounted: function() {
    this.openScan()
  },
  unmounted: function() {
    this.codeReader.reset() // 关闭摄像头
  }
}
</script>

<style lang="scss">
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.scan {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #ff9900;
  width: 100vw;
  height: 100vh;
  background: #000;
  .video-container {
    margin-top: 35%;
    display: flex;
    justify-content: center;
    video {
      width: 96vw;
      max-height: 80vh;
    }
    @media (min-width: 500px) {
      video {
        // width: 80vh;
        max-width: 96vw;
        height: 80vh;
      }
    }
  }
}
</style>
